/**
 * ...
 * >author		João Vítor de Souza
 */

package com.cupcakeengine.core 
{
	import flash.display.DisplayObject;
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;
	import flash.utils.getDefinitionByName;

	public class ReusablePool extends EventDispatcher 
	{
		// ___________________________________________________________________ CONSTANTS
		
		// ___________________________________________________________________ CLASS PROPERTIES
		
		private var _dPool				: Dictionary;		
		
		// ___________________________________________________________________ INSTANCE PROPERTIES
		
		private static var _instance	: ReusablePool;
		
		// ___________________________________________________________________ GETTERS AND SETTERS
		
		// ___________________________________________________________________ CONSTRUCTOR
		
		public function ReusablePool (singleton:SingletonObligate) {}
		
		// ___________________________________________________________________ PUBLIC METHODS
		
		public static function getInstance () : ReusablePool
		{
			if (!ReusablePool._instance) ReusablePool._instance = new ReusablePool(new SingletonObligate());
			return ReusablePool(ReusablePool._instance);
		}
		
		public function getReusable(id:String):*
		{
			checkVars(id);			
			
			var v:Vector.<Reusable> = _dPool[id];
			var len:int = v.length;
			
			for (var i:int = 0; i < len; i++) {	
				if(v[i].isFree){
					v[i].isFree = false;					
					return v[i].data;					
				}
			}			
			
			return null;
		}
		
		public function add(id:String, data:*, isFree:Boolean = true):*
		{
			checkVars(id);
			
			var obj:Reusable = new Reusable(data, isFree)
			
			var v:Vector.<Reusable> = _dPool[id];
			v.push(obj);
			_dPool[id] = v;
			
			return data;
		}
		
		public function release(className:String, data:*):void
		{
			var v:Vector.<Reusable> = _dPool[className]
			var len:int = v.length;
			
			for (var i:int = 0; i < len; i++) {
				if (v[i].data == data) {
					v[i].isFree = true;					
					break;
				}
			}
		}
		
		// ___________________________________________________________________ PRIVATE METHODS
		
		private function checkVars(className:String):void
		{			
			if (_dPool == null) _dPool = new Dictionary();
			
			if (_dPool[className] == null) _dPool[className] = new Vector.<Reusable>;
		}
		
		// ___________________________________________________________________ EVENTS
	}
}

class SingletonObligate {}
